﻿namespace FIMTestCasesDriver
{
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Management;

    public static class ConnectorSpaceHelper
    {
        private static readonly ManagementScope FIMWmiNameSpace =
            new ManagementScope("root\\MicrosoftIdentityIntegrationServer");

        private static readonly FIMEntities FIMEntities = new FIMEntities();

        public static bool IsCsEntryConnectedToMvEntry(
            Guid mvEntryGuid,
            string csEntryDN,
            string maName)
        {
            Guid csEntryGuid;
            Guid maGUID;

            if (!TryToGetMAGuid(maName, out maGUID))
            {
                throw new Exception(
                    string.Format("Unable to find MAGuid for MAName:{0} in TryToGetCsEntryGuid", maName));
            }

            if (!TryToGetCsEntryGuid(csEntryDN, maGUID, out csEntryGuid))
            {
                return false;
            }

            return (from link in FIMEntities.mms_csmv_link
                    where link.mv_object_id == mvEntryGuid && link.cs_object_id == csEntryGuid
                    select link).Count() == 1;
        }

        private static bool TryToGetMAGuid(string maName, out Guid maGUID)
        {
            maGUID = (from ma in FIMEntities.mms_management_agent 
                      where ma.ma_name == maName 
                      select ma.ma_id).Single();
            return true;
        }

        private static bool TryToGetCsEntryGuid(
            string csEntryDN,
            Guid maGUID,
            out Guid csEntryGUID)
        {
            var csQueryString = string.Format(
                CultureInfo.CurrentCulture, "DN='{0}' and MaGuid='{{{1}}}'", csEntryDN, maGUID);
                   
            var csQuery = new SelectQuery("MIIS_CSObject", csQueryString);
            var csSearcher = new ManagementObjectSearcher(FIMWmiNameSpace, csQuery);
            var csObjects = csSearcher.Get();

            if (csObjects.Count > 1)
            {
                throw new Exception(string.Format("Multiple connectors for the same DN detected{0}", csEntryDN));
            }

            if (csObjects.Count == 0)
            {
                csEntryGUID = Guid.Empty;
                return false;
            }

            var guid = string.Empty;
            foreach (ManagementObject csObject in csObjects)
            {
                guid = csObject["Guid"].ToString();
                break;
            }

            csEntryGUID = new Guid(guid);
            return true;
        }
    }
}
